import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../services/dio_service.dart';
import '../models/share_request.dart';
import '../models/share_response.dart';
import '../utils/encryption_util.dart';
import '../services/user_service.dart';

/// 🔗 分享相关API
/// 
/// 对应后端的分享功能接口
class ShareApi {
  
  // 📡 网络服务实例
  static DioService get _dioService => Get.find<DioService>();
  
  /// 创建分享链接（使用AES加密）
  /// 
  /// [shareTitle] 分享标题
  /// [userId] 用户ID
  /// [userNickname] 用户昵称
  /// [userGender] 用户性别
  /// [userCity] 用户城市
  /// [userAvatarUrl] 用户头像URL
  /// [contentType] 内容类型：'activity'（活动）、'comment'（评论）
  /// [contentTitle] 内容标题
  /// [contentText] 内容描述
  /// [contentImages] 内容图片列表
  /// 
  /// 返回分享链接信息
  static Future<ShareResponse> createShare({
    required String shareTitle,
    required String userId,
    required String userNickname,
    required String userGender,
    required String userCity,
    required String userAvatarUrl,
    required String contentType,
    required String contentTitle,
    required String contentText,
    required List<String> contentImages,
  }) async {
    try {
      debugPrint('🔄 =============== 开始创建分享链接（AES加密） ===============');
      debugPrint('🎯 内容类型: $contentType');
      debugPrint('📝 内容标题: $contentTitle');
      debugPrint('👤 用户昵称: $userNickname');

      // 🔥 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000);

      // 🔥 创建请求模型
      final request = ShareRequest(
        shareTitle: shareTitle,
        userId: userId,
        userNickname: userNickname,
        userGender: userGender,
        userCity: userCity,
        userAvatarUrl: userAvatarUrl,
        contentType: contentType,
        contentTitle: contentTitle,
        contentText: contentText,
        contentImages: contentImages,
        timestamp: timestamp,
      );

      // 获取请求数据
      final requestData = request.toJson();
      debugPrint('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      debugPrint('🔐 开始AES加密分享数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      debugPrint('🚀 准备发送加密请求到: /share/create/');

      // 发送请求
      final response = await _dioService.post(
        '/share/create/',
        data: encryptedPayload,
      );

      debugPrint('📨 分享创建响应: $response');

      // 解析响应
      final shareResponse = ShareResponse.fromJson(response.data);

      if (shareResponse.isSuccess) {
        debugPrint('✅ 分享链接创建成功');
        debugPrint('🔗 分享URL: ${shareResponse.data?.shareUrl}');
        debugPrint('🆔 分享ID: ${shareResponse.data?.shareId}');
      } else {
        debugPrint('❌ 分享链接创建失败: ${shareResponse.message}');
      }

      return shareResponse;
    } catch (e) {
      debugPrint('💥 创建分享链接异常: $e');
      return ShareResponse(
        status: 'error',
        message: '创建分享链接失败: ${e.toString()}',
      );
    }
  }

  /// 创建活动分享链接（便捷方法）
  /// 
  /// 自动获取当前用户信息并格式化活动数据
  static Future<ShareResponse> createActivityShare({
    required String activityTitle,
    required String activityText,
    required List<String> activityImages,
  }) async {
    // 🔥 获取当前用户信息
    final userService = UserService.to;
    final currentUser = userService.currentUserProfile;
    
    if (currentUser == null) {
      return ShareResponse(
        status: 'error',
        message: '请先登录',
      );
    }

    return createShare(
      shareTitle: '我在玩真的发现了一个有趣的活动，快来看看吧！',
      userId: currentUser.userid.toString(),
      userNickname: currentUser.username ?? '玩真的用户',
      userGender: currentUser.userGender ?? '',
      userCity: currentUser.userCity ?? '',
      userAvatarUrl: currentUser.userAvatarUrl ?? '',
      contentType: 'activity',
      contentTitle: activityTitle,
      contentText: activityText,
      contentImages: activityImages,
    );
  }

  /// 获取分享统计信息（可选功能）
  static Future<Map<String, dynamic>> getShareStats({
    required int shareId,
  }) async {
    try {
      debugPrint('🔄 =============== 开始获取分享统计（AES加密） ===============');
      debugPrint('🎯 分享ID: $shareId');

      final requestData = {
        'shareId': shareId,
      };

      debugPrint('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      debugPrint('🚀 准备发送加密请求到: /share/stats/');

      // 发送请求
      final response = await _dioService.post(
        '/share/stats/',
        data: encryptedPayload,
      );

      debugPrint('📨 分享统计响应: ${response.data}');

      if (response.data is Map<String, dynamic> && response.data['status'] == 'success') {
        debugPrint('✅ 分享统计获取成功');
        return response.data;
      } else {
        debugPrint('❌ 分享统计获取失败');
        return {
          'status': 'error',
          'message': '获取分享统计失败',
        };
      }
    } catch (e) {
      debugPrint('💥 获取分享统计异常: $e');
      return {
        'status': 'error',
        'message': '获取分享统计失败: ${e.toString()}',
      };
    }
  }
}

